package ru.stepuk.modern.nodes;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import ru.stepuk.modern.InvalidModelException;
import ru.stepuk.modern.Model;
import ru.stepuk.modern.Path;
import ru.stepuk.modern.Request;
import ru.stepuk.modern.generators.RandomNumberGenerator;

/**
 *
 * @author ivan
 */
public class RandomCond extends Node {

    //private Node[] next;
    private RandomNumberGenerator rng;
    private Path[] paths;
    private double wsum;

    {
        icon = icon = new ImageIcon(getClass().getResource("/images/c_random.png"));
    }

    public RandomCond(Model model, RandomNumberGenerator rng) {
        super(model);
        this.rng = rng;
    }

    public Path nextPath() {
        double rnd = rng.nextValue();
        double sum = 0;

        for (int i = 0; i < paths.length - 1; i++) {
            sum += (paths[i].getWeight() / wsum);
            if (rnd < sum) {
                return paths[i];
            }
        }
        return paths[paths.length - 1];

    }

    @Override
    public void processRequest(Request request) {
        model.getNodeByPath(nextPath()).processRequest(request);
    }

    @Override
    public void validate() throws InvalidModelException {
        paths = null;


        if (model.getNextNodes(this).size() == 0) {
            throw new InvalidModelException(this.name + ": No out from node");
        } else {


            paths = model.getOutcome(this).toArray(new Path[0]);
            wsum = 0;

            for (int i = 0; i < paths.length; i++) {
                wsum += paths[i].getWeight();

            }
        }
    }

    @Override
    public JDialog getPropertiesDialog() {
         return null;
    }
}
